package com.zyz.common.utils.word;


import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * word模板
 * ty
 * 2021/08/27
 * http://deepoove.com/poi-tl/官方文档
 */
public class WordTemplateUtils {
    public static void main(String[] args) throws IOException {
        System.out.println(System.getProperty("user.dir"));
//        List<String > list1=new ArrayList();
//        list1.add("张三");
//        list1.add("张三");
//        list1.add("李四");
//        list1.add("王五");
//        List<String > list2=new ArrayList();
//        list2.add("王五");
//        list2.add("张三");
//        list2.add("张三");
//        list2.add("李四");
//        System.out.println(list1.retainAll(list2));
//        list1.sort(Comparator.comparing(String::hashCode));
//        list2.sort(Comparator.comparing(String::hashCode));
//        System.out.println(list1.equals(list2));
//        System.out.println(System.getProperty("user.dir"));
//        test();
        WordTemplateUtils muDemo = new WordTemplateUtils();
//        try {
        muDemo.showURL();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

//     String filePath = "E:\\test\\劳务合同-通用.docx";
//     File file=new File(filePath);
//        String s = readDocx(file);
//        System.out.println();
//        if (filePath.endsWith(".doc")){
//            System.out.println("11");
//        }
//        System.out.println(count(s,"{{"));
    }

    /**
     * ty
     * 2021/8/30
     * 对比两个数据是否==
     *
     * @return
     */
    public static Map compareString(MultipartFile file, String dateName, Class clazz) throws IOException {
        Map map = new HashMap();
        FileInputStream inputStream = new FileInputStream(System.getProperty("user.dir") + File.separator + "wordTemplates" + File.separator + dateName + ".docx");
//        ClassPathResource classPathResource = new ClassPathResource(
//                "wordTemplates" + File.separator + dateName + ".docx");
//        InputStream inputStream = classPathResource.getInputStream();
        if (inputStream == null) {
            System.out.println("++++++++====++++++++");
        }
        String sTemplate = readWord(inputStream, dateName + ".docx");
        String fTemplate = readWord(file.getInputStream(), file.getOriginalFilename());
        inputStream.close();
        Map sMap = mapCounts(sTemplate, "{{", "}}");
        Map fMap = mapCounts(fTemplate, "{{", "}}");
        if (sMap == null || fMap == null) {
            map.put("code", "500");
            map.put("date", "未读取到文件信息");
        }
        //原模板
        Integer sCount = (Integer) sMap.get("count");
        List<String> sLists = (List<String>) sMap.get("list");
        //上传模板
        Integer fCount = (Integer) fMap.get("count");
        List<String> fLists = (List<String>) fMap.get("list");
        if (!sCount.equals(fCount)) {
            map.put("code", "500");
            map.put("date", "请勿改变属性数量");
        }
        sLists.sort(Comparator.comparing(String::hashCode));
        fLists.sort(Comparator.comparing(String::hashCode));
        boolean equals = sLists.equals(fLists);
        if (equals) {
            map.put("code", "200");
            map.put("date", "数据一致");
        } else {
            map.put("code", "500");
            map.put("date", "数据不一致");
        }
        return map;
    }

    /**
     * 判断内容中的参数出现几次
     *
     * @param property
     * @return
     */
    public static Map<String, Integer> getCharMaps(List<String> property) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (String pro : property) {
            Integer count = map.get(pro);
            map.put(pro, count == null ? 1 : count + 1);
        }
        return map;
    }

    /**
     * ty
     * 2021/8/29
     * 统计该字段出现了多少次
     *
     * @param text
     * @param sub
     * @return
     */
    public static int counts(String text, String sub) {
        int count = 0, start = 0;
        while ((start = text.indexOf(sub, start)) >= 0) {
            start += sub.length();
            count++;
        }
        return count;
    }

    public static Map mapCounts(String text, String sub, String endSub) {
        Map map = new HashMap();
        List<String> list = new ArrayList();
        int count = 0, start = 0;
        while ((start = text.indexOf(sub, start)) >= 0) {
            String substring = text.substring(start, text.indexOf(endSub, start));
            list.add(substring);
            start += sub.length();
            count++;
        }
        map.put("count", count);
        map.put("list", list);
        return map;
    }

    /**
     * ty
     * 2021/08/29
     * java各种获取路劲方法
     *
     * @throws IOException
     */
    public void showURL() throws IOException {
        // 第一种：获取类加载的根路径   D:\git\daotie\daotie\target\classes
        File f = new File(this.getClass().getResource("/").getPath());
        System.out.println(f);
        System.out.println("++++++++++++++++++++++++1");

        // 获取当前类的所在工程路径; 如果不加“/”  获取当前类的加载目录  D:\git\daotie\daotie\target\classes\my
        File f2 = new File(this.getClass().getResource("").getPath());
        System.out.println(f2);
        System.out.println("++++++++++++++++++++++++2");
        // 第二种：获取项目路径    D:\git\daotie\daotie
        File directory = new File("");// 参数为空
        String courseFile = directory.getCanonicalPath();
        System.out.println(courseFile);
        System.out.println("++++++++++++++++++++++++3");

        // 第三种：  file:/D:/git/daotie/daotie/target/classes/
        URL xmlpath = this.getClass().getClassLoader().getResource("");
        System.out.println(xmlpath);
        System.out.println("++++++++++++++++++++++++4");

        // 第四种： D:\git\daotie\daotie
        System.out.println(System.getProperty("user.dir"));
        /*
         * 结果： C:\Documents and Settings\Administrator\workspace\projectName
         * 获取当前工程路径
         */
        System.out.println("++++++++++++++++++++++++5");
        // 第五种：  获取所有的类路径 包括jar包的路径
        System.out.println(System.getProperty("java.class.path"));

    }


    public static void test() throws IOException {
        File fileInputStream = new File("E:\\test\\劳务合同-通用.docx");
        FileInputStream fileInputStream1 = new FileInputStream("E:\\test\\劳务合同-通用.docx");
        Map<String, Object> data = new HashMap<>();
        data.put("cpName", "汤汤有限");
        XWPFTemplate template = XWPFTemplate.compile(fileInputStream)
                .render(data);
        FileOutputStream out;
        out = new FileOutputStream("E:\\test\\劳务合同5.pdf");
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
//        template.write(out);
        template.write(bout);
//        byte[] bytes = bout.toByteArray();
        byte[] byt = Word2PdfUtils.convertPdf(fileInputStream1);
        bout.close();
        out.write(byt);
        out.flush();
        out.close();
        template.close();


    }

    /**
     * ty
     * 2021/8/29
     * word模板生成文件
     *
     * @param bytes word文件数组
     * @param data
     * @return
     * @throws IOException
     */
    public static ByteArrayOutputStream wordTemplate(byte[] bytes, Map data) throws IOException {
        ByteArrayInputStream bit = new ByteArrayInputStream(bytes);
        XWPFTemplate template = XWPFTemplate.compile(bit)
                .render(data);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        template.write(bout);
        bout.flush();
        bout.close();
        template.close();
        return bout;
    }

    /**
     * ty
     * 2021/8/29
     * word模板生成文件
     *
     * @param bytes word文件数组
     * @param data
     * @return
     * @throws IOException
     */
    public static ByteArrayOutputStream wordTemplateTable(byte[] bytes, Map data, String table) throws IOException {
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        ByteArrayInputStream bit = new ByteArrayInputStream(bytes);
        Configure config = Configure.builder()
                .bind(table, policy).build();
        XWPFTemplate template = XWPFTemplate.compile(bit, config).render(data);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        template.write(bout);
        bout.flush();
        bout.close();
        template.close();
        return bout;
    }

    /**
     * ty
     * 2021/8/28
     * name 模板名称
     * 调用word转pdf
     */
    public static byte[] wordTemplateByte(String name, Class clazz) throws IOException {
//        ClassPathResource classPathResource = new ClassPathResource(
//                "wordTemplates" + File.separator + name + ".docx");
//        InputStream inputStream = classPathResource.getInputStream();
        FileInputStream inputStream = new FileInputStream(System.getProperty("user.dir") + File.separator + "wordTemplates" + File.separator + name + ".docx");
        System.out.println(System.getProperty("user.dir") + File.separator + "wordTemplates" + File.separator + name + ".docx");
        if (inputStream == null) {
            System.out.println("++++++++====++++++++");
        }
        byte[] byt = Word2PdfUtils.convertPdf(inputStream);
        inputStream.close();
        return byt;
    }


    /**
     * ty
     * 2021/8/28
     * name 模板名称
     * 下载word模板
     */
    public static byte[] downloadWordByte(String name, Class clazz) throws IOException {
//        ClassPathResource classPathResource = new ClassPathResource(
//                "wordTemplates" + File.separator + name + ".docx");
//        InputStream inputStream = classPathResource.getInputStream();
        FileInputStream inputStream = new FileInputStream(System.getProperty("user.dir") + File.separator + "wordTemplates" + File.separator + name + ".docx");
        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
        inputStream.close();
        return bytes;
//        return byteArrayOutputStream.toByteArray();
    }

    public static ByteArrayOutputStream byteArray(InputStream input) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
        } catch (IOException e) {
        } finally {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
        return baos;
    }

    /**
     * 读取word文件内容信息
     *
     * @param inputStream
     * @param fileName
     * @return
     */
    public static String readWord(InputStream inputStream, String fileName) {
        if (fileName.endsWith(".doc")) {
            return readDoc(inputStream);
        } else {
            return readDocx(inputStream);
        }
    }

    /**
     * ty
     * 2021/08/29
     * 读取word文件中的内容
     *
     * @param inputStream
     * @return
     */
    public static String readDocx(InputStream inputStream) {
        System.out.println("....docx");
        String str = "";
        try {
            XWPFDocument xdoc = new XWPFDocument(inputStream);
            XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
            str = extractor.getText();
//            System.out.println(str);
            extractor.close();
            xdoc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return str;

    }

    public static String readDoc(InputStream inputStream) {
        System.out.println("....doc");
        String text = "";
        try {
            WordExtractor extractor = new WordExtractor(inputStream);
            text = extractor.getText();
            extractor.close();
        } catch (Exception e) {
            System.out.println("Word解析错误！");
        }
        return text;

    }

}
